package cn.edu.ctbu.datajpa01.restcontroller;

import cn.edu.ctbu.datajpa01.domain.Student;
import cn.edu.ctbu.datajpa01.helper.PageUtils;
import cn.edu.ctbu.datajpa01.helper.Result;
import cn.edu.ctbu.datajpa01.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;



@Slf4j
@RestController
@RequestMapping("/student/webapi/student")
public class StudentRestController {


    @Autowired
    private StudentService studentService;

    @GetMapping("/list")
    public PageUtils GetAll(Integer pageSize, Integer pageNum) {
        Pageable pageable = PageRequest.of(pageNum-1,pageSize);
        Page<Student> tempStudents = studentService.getAll(pageable);
        PageUtils pageUtils=new PageUtils(tempStudents.getTotalElements(),tempStudents.getContent());

        return pageUtils;
    }

    @GetMapping("/get/{id}")
    public Student get(@PathVariable Integer id) {
        Student student = studentService.findById(id);
        student.setPassword("");
        return student;
    }


    @PostMapping("/insert")
    public Student insert(@Valid Student student, BindingResult bindingResult) {
        if(bindingResult.hasErrors()) {
            log.info(bindingResult.getFieldError().getDefaultMessage());
        }

        Student student1=studentService.insert(student);
        return student1;
    }

    @PutMapping("/update")
    public Student update(Student student) {
        Student oldstudent=studentService.findById(student.getId());
        if(StringUtils.isEmpty(student.getPassword())){
            oldstudent.setPassword(oldstudent.getPassword());
        }
        student=studentService.update(student);
        return student;
    }

    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable Integer id) {
        studentService.delete(id);
    }

    @GetMapping("login")
    public Result login(String username, String password) throws Exception{

        studentService.validUserNameAndPassword(username,password);
        return Result.ok();

    }





}